package com.viroyal.monitorlib.service;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.suntiago.baseui.utils.log.CrashHandler;
import com.suntiago.baseui.utils.log.Slog;
import com.viroyal.monitorlib.CommandControl;
import com.viroyal.monitorlib.core.DownloadManager;
import com.viroyal.monitorlib.core.DownloadService;
import com.viroyal.monitorlib.db.DBController;
import com.viroyal.monitorlib.entity.ApiConfig;
import com.viroyal.monitorlib.entity.AppInfo;
import com.viroyal.monitorlib.entity.DownloadEntry;
import com.viroyal.monitorlib.entity.HBbean;
import com.viroyal.monitorlib.entity.UploadTable;
import com.viroyal.monitorlib.entity.VersionUpgradeExtra;
import com.viroyal.monitorlib.entity.rx.RxDownloadUpdate;
import com.viroyal.monitorlib.entity.rx.RxHostChanged;
import com.viroyal.monitorlib.entity.rx.RxInstall;
import com.viroyal.monitorlib.entity.rx.Rxlog;
import com.viroyal.monitorlib.network.Api;
import com.viroyal.monitorlib.network.rsp.VersionResponse;
import com.viroyal.monitorlib.notify.DataChanger;
import com.viroyal.monitorlib.notify.DataWatcher;
import com.viroyal.monitorlib.rxpermissions.RxPermissions;
import com.viroyal.monitorlib.silent.SilentInstall;
import com.viroyal.monitorlib.utils.AppUtils;
import com.viroyal.monitorlib.utils.Constants;
import com.viroyal.monitorlib.utils.DataCleanManager;
import com.viroyal.monitorlib.utils.MD5Util;
import com.viroyal.monitorlib.utils.SPUtils;
import com.viroyal.monitorlib.utils.SystemUtils;
import com.viroyal.monitorlib.utils.ToastMgr;
import org.kymjs.kjframe.KJDB;
import java.io.File;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by cxy_nj on 2016/9/1.
 */
public class MainStartService extends Service {
    private static final String TAG = "MainStartService";
    public static final String ASSIT = "com.viroyal.vdrive.assist";
    public static final String WECHAT = "com.viroyal.webwx";
    private DownloadEntry entry;
    private VersionResponse mVersionResponse;
    private boolean isWechat;
    private boolean isVdrive;
    private VersionUpgradeExtra mUpgradeExtra;
    private Gson mGson;
    public static MyHandler mMyHandler;
    private List<AppInfo> appInfoList = new ArrayList<>();
    CommandControl mCommandControl;
    NetWorkChangeBroadcastReceiver mNetWorkChangeBroadcastReceiver;
    MonitBroadcast mMonitBroadcast = new MonitBroadcast();
    private static final int MSG_WHAT_CHECK = 101;
    private static final int MSG_TOP_CHECK = 102;
    private static final int MSG_TOP_CHECK_1 = 103;
    public static final int MSG_TOP_PACKAGE = 188;
    private boolean isExit = false;
    private ExecutorService singleThreadExecutor;

    public class MyBinder extends Binder {

        public MainStartService getService() {
            return MainStartService.this;
        }

    }

    private MyBinder binder = new MyBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //接收从activity传递过来的值
        isExit = intent.getBooleanExtra("exit", false);
        Slog.d("MainStartService", "onBind");
        return binder;
    }

    private DataWatcher dataWatcher = new DataWatcher() {

        @Override
        public void onDataChanged(DownloadEntry data) {
            entry = data;
            ToastMgr.builder.display("正在下载" + entry.percent + "%", Toast.LENGTH_SHORT);
        }
    };

    public static class MyHandler extends Handler {

        WeakReference<MainStartService> s;

        public MyHandler(MainStartService a) {
            s = new WeakReference<>(a);
        }

        @Override
        public void handleMessage(Message msg) {
            MainStartService a = s.get();
            if (a != null) {
                a.handlemsg(msg);
            }
        }
    }

    private void handlemsg(Message msg) {
        if (msg.what == 12) {
            Runnable runnable = () -> {
                if (mCommandControl != null) {
                    mCommandControl.send(HBbean.build().hB().dev(MainStartService.this).toString());
//                mDeepStem.simulateUpdate();
                }
            };
            singleThreadExecutor.execute(runnable);

            mMyHandler.sendEmptyMessageDelayed(12, 120000);
        } else if (msg.what == MSG_WHAT_CHECK) {
            //定时检查连接状态、安装应用状态。
            mMyHandler.sendEmptyMessageDelayed(MSG_WHAT_CHECK, 60000);
            Runnable runnable = () -> {
                    if (mCommandControl != null) {
                        mCommandControl.checkConnect();
                        mCommandControl.checkInstall();
                }
            };
            singleThreadExecutor.execute(runnable);
        } else if (msg.what == MSG_TOP_CHECK) {
            //定时检查top状态。
            mMyHandler.sendEmptyMessageDelayed(MSG_TOP_CHECK, 30000);
            Runnable runnable = () -> {
                    if (mCommandControl != null) {
                        mCommandControl.checkTop(MSG_TOP_CHECK);
                    }
            };
            singleThreadExecutor.execute(runnable);
        } else if (msg.what == MSG_TOP_CHECK_1) {
            //第一次定时检查top状态。
            mMyHandler.sendEmptyMessageDelayed(MSG_TOP_CHECK, 15000);
            Runnable runnable = () -> {
                    if (mCommandControl != null) {
                        mCommandControl.checkTop(MSG_TOP_CHECK_1);
                    }
            };
            singleThreadExecutor.execute(runnable);
        } else if (msg.what == MSG_TOP_PACKAGE) {
            //每隔5秒检查一次APP是否在前台或者APP进程是否存在
            mMyHandler.sendEmptyMessageDelayed(MSG_TOP_PACKAGE, 5000);
            Runnable runnable = () -> {
                if (mCommandControl != null) {
                    mCommandControl.checkTopPackage();
                }
            };
            singleThreadExecutor.execute(runnable);
        }
    }

    private void uploadFile(String id, String filepath, String pkgName, String action) {

        if (TextUtils.isEmpty(id)) {
            id = System.currentTimeMillis() + "";
        }
        UploadTable u = new UploadTable(action, 1, filepath, id, System.currentTimeMillis(), pkgName);
        KJDB.getDefaultInstance().save(u);

        Slog.d(TAG, "uploadFile  [id, filepath, pkgName, action]:");
        RxPermissions.getInstance(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(granted -> {
            if (granted) {
                if (mCommandControl != null) {
                    mCommandControl.upload(u.id_server, filepath, pkgName, action);
                } else {
                    Slog.e(TAG, "uploadFile: mDeepStem == null");
                }
            } else {
                Slog.d(TAG, "uploadFile  [id, filepath, pkgName, action]:");
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Slog.d("MainStartService", "onCreate");
        mNetWorkChangeBroadcastReceiver = new NetWorkChangeBroadcastReceiver();
        mNetWorkChangeBroadcastReceiver.register(this);
        mMonitBroadcast.register(this);
        ToastMgr.builder.init(this);
        singleThreadExecutor = Executors.newFixedThreadPool(3);
        mGson = new Gson();
        RxBus.get().register(this);
        initService();
        DataCleanManager.cleanPackages();//清除下载安装包
    }

    private void checkCrashFile() {
        try {
            File[] file = new File(CrashHandler.getInstance().getCrashLogPath()).listFiles();//读取文件夹下文件
            if (null != file && file.length != 0) {
                DateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
                String time = formatter.format(new Date());
                List<String> paths = new ArrayList<>();
                for (File value : file) {
                    if (value.getPath().contains(time)) {
                        paths.add(value.getPath());
                    }
                }
                if (paths.size() != 0) {
                    Intent intent = new Intent("com.viroyal.permission.crash_log_update");
                    intent.putExtra("pkgName", getPackageName());

                    intent.putExtra("path", paths.get(paths.size()-1));
                    sendBroadcast(intent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Slog.d(TAG, "checkCrashFile: Exception " + e.toString());
        }
    }


    public void initService() {
        String apiConfig = SPUtils.getInstance(getApplicationContext()).get("api_config");
        Api.get().deviceId = SPUtils.getInstance(this).get("mac");
        if (!TextUtils.isEmpty(apiConfig)) {
            Gson gson = new Gson();
            ApiConfig ac = gson.fromJson(apiConfig, ApiConfig.class);
            Api.get().setApi(ac.api + "/");
            Api.get().setApiConfig(ac.api + "/", ac.netty_host, ac.netty_port, ac.school_id);
            Slog.d(TAG, "init:apiHost:" + Api.DEFAULT_HOST);
            Api.init(getApplicationContext());
            mMyHandler = new MyHandler(this);
            //当前不发送心跳
            //mMyHandler.sendEmptyMessageDelayed(12, 10000);
            //当前并没有用11的消息
            //mMyHandler.sendEmptyMessageDelayed(11, 10000);

            //启动连接检查,top、installed检测
            mMyHandler.sendEmptyMessageDelayed(MSG_TOP_CHECK_1, 30000);
            mMyHandler.sendEmptyMessageDelayed(MSG_WHAT_CHECK, 10000);
            mMyHandler.sendEmptyMessageDelayed(MSG_TOP_PACKAGE, 5000);
            mCommandControl = new CommandControl(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Slog.d(TAG, "onDestroy()");
        RxBus.get().unregister(this);
        stopService(new Intent(this, DownloadService.class));
        mNetWorkChangeBroadcastReceiver.unregister(this);
        mMonitBroadcast.unRegister();
        singleThreadExecutor.shutdownNow();
        if (isExit) {
            stopSelf();
            android.os.Process.killProcess(android.os.Process.myPid());
        } else {
            startService(new Intent(getApplicationContext(), MainStartService.class).putExtra("apichanged", 1));
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void updateHostChange(RxHostChanged rxInstall) {
        if (mCommandControl != null) {
            mCommandControl.hostChange();
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void update(Rxlog rxlog) {

    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void apkInstalled(RxInstall rxInstall) {
        if (mCommandControl != null) {
            mCommandControl.apkInstalled(rxInstall);
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("send_msg")})
    public void sendMsg(String msg) {
        if (mCommandControl != null) {
            mCommandControl.send(msg);
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void apkDownloading(RxDownloadUpdate rxInstall) {
        if (mCommandControl != null) {
            mCommandControl.updateInstallDownloadRes(rxInstall.pkg_name, rxInstall.progress);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Slog.d("MainStartService", "onStartCommand");
//        if (!AppUtils.isAccessibilitySettingsOn2(this)) {
//            Intent intent1 = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
//            intent1.addFlags(FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent1);
//        }

        //检查本地是否有crash文件,有就发广播上传至后台
        checkCrashFile();

        String url = null;
        if (intent != null) {
            if (intent.getIntExtra("apichanged", -1) == 1) {
                initService();
            }
            url = intent.getStringExtra("version_upgrade");
        }
        if (!TextUtils.isEmpty(url)) {
            mUpgradeExtra = mGson.fromJson(url, VersionUpgradeExtra.class);
            if (mUpgradeExtra.is_cancel == Constants.IS_UPDATE_CANCELED) {//取消下载
                if (DataChanger.getInstance(this).containsDownloadEntry(mUpgradeExtra.apk_url)) {
                    DownloadEntry entry = DBController.getInstance(this).queryByUrl(mUpgradeExtra.apk_url);
                    DownloadManager.getInstance(this).pause(entry);
                    SPUtils.getInstance(this).put(Constants.OTHER_APK_URL, "");
                    DataChanger.getInstance(this).deleteDownloadEntryByUrl(url);
                    entry.reset();
                }
                mUpgradeExtra = null;
            } else {
                SPUtils.getInstance(this).put(Constants.OTHER_APK_URL, mUpgradeExtra.apk_url);
                if (!isVdrive && !isWechat) {
                    if (mUpgradeExtra.upgrade_mode == Constants.SILENT_MODE) {
                        startDownload(mUpgradeExtra.apk_url);
                    } else {
                        showDownloadDialog(mUpgradeExtra.upgrade_log, mUpgradeExtra.apk_url);
                    }
                }
            }
        } else {
//            checkConfigure(SystemUtils.getAppVersionCode(ASSIT, this), "vdrive_autocar");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 安装APK
     *
     * @param file
     */
    private void installApk(File file) {
        Slog.d(TAG, "installApk: path=" + file.getPath());
        if (android.os.Build.MODEL.equals("T3") || android.os.Build.MODEL.equals("T6")) {
        //班牌静默安装
        Intent intent = new Intent("install.application");
        intent.putExtra("path_name", file.getPath());
        intent.putExtra("open", 2);//如不需自启动，可将数值改为0或1
        sendBroadcast(intent);
        } else if (android.os.Build.MODEL.equals("T2") || android.os.Build.MODEL.equals("rk3288")) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri uriForFile = FileProvider.getUriForFile(this, AppUtils.getPackageName(getApplicationContext()) +
                        ".fileprovider", file);
                install.setDataAndType(uriForFile, "application/vnd.android.package-archive");
            } else {
                install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
        }
    }

    /**
     * 需要root权限，静默安装
     */
    public void onSilentInstall(File file) {
//        final SilentInstall installHelper = new SilentInstall();
//        if (!installHelper.isRoot()) {
//            installApk(Uri.parse("file://" + file.getPath()));
            installApk(file);
//            return;
//        }
//        installHelper.install(file.getPath());
    }

    //下载完成后会通知到这里，
    @Subscribe()
    public void installFile(File file) {
        Slog.d(TAG, "installFile ");
        if (mUpgradeExtra != null) {
            if (TextUtils.isEmpty(mUpgradeExtra.md5) || MD5Util.fileToMD5(file.getPath()).equals(mUpgradeExtra.md5)) {
                onSilentInstall(file);
                SPUtils.getInstance(this).put(Constants.OTHER_APK_URL, "");
                mUpgradeExtra = null;//清空extra
            }
        } else if (mVersionResponse != null) {
            if ((TextUtils.isEmpty(mVersionResponse.getExtra().getMd5()) || MD5Util.fileToMD5(file.getPath()).equals(mVersionResponse.getExtra().getMd5()))) {
                onSilentInstall(file);
                isVdrive = false;//下载结束
                mVersionResponse = null;//清空response
                if (!isWechat) {
                    isWechat = true;//开始检测微信升级
                    checkConfigure(SystemUtils.getAppVersionCode(WECHAT, this), "vdrive_wechat");
                } else {
                    isWechat = false;//微信下载结束
                    if (mUpgradeExtra != null) {//开始extra下载
                        if (mUpgradeExtra.upgrade_mode == Constants.SILENT_MODE) {
                            startDownload(mUpgradeExtra.apk_url);
                        } else {
                            showDownloadDialog(mUpgradeExtra.upgrade_log, mUpgradeExtra.apk_url);
                        }
                    } else {//继续未完成的下载
                        String otherApkUrl = SPUtils.getInstance(this).get(Constants.OTHER_APK_URL);
                        if (!TextUtils.isEmpty(otherApkUrl)) {
                            startDownload(otherApkUrl);
                        }
                    }
                }
            }
        } else if (!TextUtils.isEmpty(SPUtils.getInstance(this).get(Constants.OTHER_APK_URL))) {
            onSilentInstall(file);
            SPUtils.getInstance(this).put(Constants.OTHER_APK_URL, "");
        } else {
            Slog.d(TAG, "installFile  [file]: else");
        }

    }

    /**
     * 非静默下载时，下载就会弹出此对话框提示
     */
    private void showDownloadDialog(String log, final String apkUrl) {
        AlertDialog.Builder netBuilder = new AlertDialog.Builder(this.getApplicationContext());
        netBuilder.setTitle("升级提示");
        if (TextUtils.isEmpty(log)) {
            netBuilder.setMessage("您有新版本升级,请确认是否马上下载？");
        } else {
            netBuilder.setMessage(log);
        }
        netBuilder.setNegativeButton("取消下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (!isWechat)
                    checkConfigure(SystemUtils.getAppVersionCode(WECHAT, MainStartService.this),
                            "vdrive_wechat");
                if (isWechat) {
                    isWechat = false;
                    String otherApkUrl =
                            SPUtils.getInstance(MainStartService.this).get(Constants.OTHER_APK_URL);
                    if (!TextUtils.isEmpty(otherApkUrl)) startDownload(otherApkUrl);
                }
                if (isVdrive) {
                    isVdrive = false;
                }
            }
        });
        netBuilder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startDownload(apkUrl);
            }
        });
        AlertDialog netDialog = netBuilder.create();
        netDialog.setCanceledOnTouchOutside(false);
        /* set size & pos */
        WindowManager.LayoutParams lp = netDialog.getWindow().getAttributes();
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        Display display = wm.getDefaultDisplay();
        netDialog.getWindow().setAttributes(lp);
        netDialog.show();
    }

    private void startDownload(String url) {
        Slog.e("MainStartService", url);
        SPUtils.getInstance(MainStartService.this).put(Constants.APK_URL, url);
        entry = new DownloadEntry(url);
        entry.name = url.substring(url.lastIndexOf("/") + 1);//apk名字
        DownloadManager.getInstance(MainStartService.this).add(entry);
        DownloadManager.getInstance(MainStartService.this).addObserver(dataWatcher);
    }

    private void checkConfigure(int version, String appId) {
//        String sn = SystemProperties.get("persist.sys.phoneinfo.sn");
//        String model = "Q9";
//        if (TextUtils.isEmpty(sn)) {
//            sn = "NJ00-test-q9-cxy";
//        }
//        checkUpdate(appId, version, model, sn);
    }


    //监听网络变化
    class NetWorkChangeBroadcastReceiver extends BroadcastReceiver {
        public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn" +
                ".CONNECTIVITY_CHANGE";

        @Override
        public void onReceive(Context context, Intent intent) {
            Slog.d(TAG, "onReceive, intent action = " + intent.getAction());
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                Slog.d(TAG, "onReceive  [context, intent]:networkInfo.isConnected()");
            } else {
                Slog.d(TAG, "onReceive  [context, intent]:networkInfo.disConnected()");
            }
        }

        public void register(Context context) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(CONNECTIVITY_CHANGE_ACTION);
            context.registerReceiver(this, filter);
        }

        public void unregister(Context context) {
            context.unregisterReceiver(this);
        }
    }

    private String rid = "";
    private String rpkgName = "";

    //设备监听接口
    public class MonitBroadcast extends BroadcastReceiver {
        private static final String TAG = "MonitBroadcast";
        private String sPath;
//        private final static String LOG_PATH = "/viroyal/com.viroyal.monitor/";// 日志文件在sdcard中的路径
//        private final static String LOG_FILE_FIRST_NAME = "com_viroyal_monitor_";
        private final static String LOG_FILE_END_NAME = "_log.txt";
        Context mContext;
        private String mLogId;
        private String mRestartId;
        //截屏完成广播
        public static final String CAPTURE_COMPLETE = "com.viroyal.permission.capture_complete";
        //CRASH_LOG
        public static final String CRASH_LOG_UPDATE = "com.viroyal.permission.crash_log_update";
        //crash日志上传
        public static final String LOG_UPDATE = "com.viroyal.permission.sendlog";//日志上传
        public static final String GET_LOG = "com.viroyal.permission.getlog";//获取日志
        public static final String RESTART_COMPLETE = "com.viroyal.permission.restart_complete";
        //重启成功广播
        public static final String START_COMPLETE = "com.viroyal.permission.start_complete";

        public static final String TOP_CHANGED = "com.viroyal.permission.topchanged";
        public static final String STOP_SERVICE = "com.viroyal.permission.stopservice";
        public static final String START_SERVICE = "com.viroyal.permission.startservice";
        @Override
        public void onReceive(Context context, Intent intent) {
            Slog.d(TAG, "MonitBroadcast:onReceive  [context, intent]:" + intent.getAction());
            switch (intent.getAction()) {
                case CAPTURE_COMPLETE:
                    Slog.d("Screenshot :", "MonitBroadcast:" + CAPTURE_COMPLETE);
                    String path = intent.getStringExtra("path");
                    String pkgName = intent.getStringExtra("pkgName");
                    String ret = intent.getStringExtra("ret");
                    String msg = intent.getStringExtra("msg");
                    String id = intent.getStringExtra("id");
                    Slog.d(TAG,
                            "MonitBroadcast:onReceive  [context, intent]:" + " path:" + path + " " +
                                    "pkgName:" + pkgName + " " + "ret:" + ret + " msg:" + msg +
                                    " id:" + id + "");

                    Runnable runnable = () -> uploadFile(id, path, pkgName, "capture");
                    new Thread(runnable).start();
                    break;
                case CRASH_LOG_UPDATE:
                    path = intent.getStringExtra("path");
                    pkgName = intent.getStringExtra("pkgName");
                    Slog.d(TAG,
                            "onReceive  [context, intent]:" + " path:" + path + " pkgName:" + pkgName);
                    uploadFile(null, path, pkgName, "log-upload");
                    break;
                case LOG_UPDATE:
                    Slog.d(TAG, "onReceive: " + LOG_UPDATE);
                    path = intent.getStringExtra("path");
                    pkgName = intent.getStringExtra("pkgName");
                    id = intent.getStringExtra("id");
                    Slog.d(TAG,
                            "onReceive  [context, intent]:" + " path:" + path + " pkgName:" + pkgName + " id:" + id + "");
                    uploadFile(id, path, pkgName, "get-log");
                    break;
                case RESTART_COMPLETE:
                    Slog.d(TAG, "onReceive: " + RESTART_COMPLETE);
                    id = intent.getStringExtra("id");
                    pkgName = intent.getStringExtra("pkgName");
                    int status = Integer.valueOf(intent.getStringExtra("status"));
                    if (!id.equals("")) {
                        mCommandControl.updateRestart(id, pkgName, status);
                    }

//            }else if(intent.getAction().equals(START_COMPLETE)){
//                if (!rid.equals("")&&!rpkgName.equals("")){
//                    if(mCommandControl.status_restart==1&&rpkgName.equals(intent.getStringExtra
//                    ("pkgName"))){
//                        Slog.d(TAG, "onReceive: "+START_COMPLETE);
//                        String id =rid;
//                        String pkgName = intent.getStringExtra("pkgName");
//                        int status = Integer.valueOf(intent.getStringExtra("status"));
//                        mCommandControl.updateRestart(id,pkgName,status);
//                        mCommandControl.status_restart = 0;
//                    }
//                }
                    break;
                case GET_LOG:
                    if (intent.getStringExtra("pkgName").equals(mContext.getPackageName())) {
                        Slog.d(TAG, GET_LOG);
                        mLogId = intent.getStringExtra("id");
                        updatelog(context);
                    }
                    break;
                case TOP_CHANGED:
                    String pkg = intent.getStringExtra("pkg");
                    String cls = intent.getStringExtra("class");
                    Slog.d(TAG, "onReceive:getClassName:[" + cls + "],getPackageName:[" + pkg +
                            "]");
                    break;
                case STOP_SERVICE://接听拨打语音电话,暂停防杀检测,防止界面被覆盖
                    mMyHandler.removeMessages(MSG_TOP_PACKAGE);
                    break;
                case START_SERVICE://挂断语音电话,开启防杀检测
                    mMyHandler.sendEmptyMessageDelayed(MSG_TOP_PACKAGE, 5000);
                    break;
            }
        }

        public void register(Context c) {
            mContext = c;
            IntentFilter filter = new IntentFilter();
            filter.addAction(CAPTURE_COMPLETE);
            filter.addAction(CRASH_LOG_UPDATE);
            filter.addAction(LOG_UPDATE);
            filter.addAction(GET_LOG);
            filter.addAction(RESTART_COMPLETE);
            filter.addAction(TOP_CHANGED);
            filter.addAction(STOP_SERVICE);
            filter.addAction(START_SERVICE);
//            filter.addAction(START_COMPLETE);
            c.registerReceiver(this, filter);
        }

        public void unRegister() {
            mContext.unregisterReceiver(this);
        }

        private void updatelog(Context context) {
            String logtime = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
            Slog.d(TAG, "updatelog:" + LOG_UPDATE);
//            String logpath = getSavePath(context) + LOG_FILE_FIRST_NAME + logtime + LOG_FILE_END_NAME;
            String logpath = Slog.getLogPath() + context.getPackageName().replace(".", "_") + "_" + logtime + LOG_FILE_END_NAME;
            Slog.d(TAG,
                    "updatelog:path:" + logpath + " id:" + mLogId + " pkgName:" + context.getPackageName());
            Intent intent = new Intent();
            intent.setAction(LOG_UPDATE);
            intent.putExtra("path", logpath);
            intent.putExtra("pkgName", context.getPackageName());
            intent.putExtra("id", mLogId);
            context.sendBroadcast(intent);
        }

//        public String getSavePath(Context context) {
//            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                sPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//            } else {
//                if (context != null) {
//                    Slog.StorageList storageList = new Slog.StorageList(context);
//                    sPath = storageList.getVolumePaths()[1];
//                }
//            }
//            return sPath + LOG_PATH;
//        }
    }
}